package com.duan.boot.service.impl;

import com.duan.boot.entity.HomePage;
import com.duan.boot.entity.User;
import com.duan.boot.mapper.HomePageMapper;
import com.duan.boot.service.HomePageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author duan
 * @date 2022/11/21 12:57
 */
@Service
public class HomePageServiceImpl implements HomePageService {
    @Resource
    private HomePageMapper homePageMapper;
    @Override
    public Map<String, String> moodCard(int id) {
        Map<String, String> map = new HashMap<>();
        map.put("todoList", homePageMapper.getById(id).getUserTodoList());
        map.put("moodCard", homePageMapper.getById(id).getUserMoodCard());
        return map;
    }

    @Override
    public Boolean updateHomePage(HomePage homePage) {
        return homePageMapper.saveHomePage(homePage);
    }

    @Override
    public Boolean removeUser(Integer id) {
        return homePageMapper.removeUser(id);
    }

    @Override
    public HomePage findByToken(String token) {
        return homePageMapper.findByToken(token);
    }

    private final static int EXPIRE = 12;
    @Override
    public String createToken(User user) {
        String token = UUID.randomUUID().toString();

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireTime = now.plusHours(EXPIRE);

        HomePage homePage = new HomePage();
        homePage.setUserLoginTime(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        homePage.setUserExpireTime(Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant()));
        homePage.setUserToken(token);
        homePage.setUserId(user.getUserId());
        updateHomePage(homePage);

        return token;
    }

    @Override
    public HomePage getById(int id) {
        return homePageMapper.getById(id);
    }


}
